package com.example.control
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.Layout
import android.util.Log
import android.view.*
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.button.MaterialButton
import com.google.android.material.navigation.NavigationView
import com.google.gson.Gson
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.IllegalArgumentException
import java.lang.StringBuilder
import java.util.zip.Inflater
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {

    private val updateConnectionText = 1
    private val updateCarMoveForward = 2

    private var isPressed = 0
    private var isPressed1 = 0
    private var isPressed2 = 0
    private var isPressed3 = 0
    private lateinit var retrofit: Retrofit
    private lateinit var controlService: Service


    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.toobar_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            android.R.id.home->{
                Toast.makeText(this, "You clicked home", Toast.LENGTH_SHORT).show()
                findViewById<DrawerLayout>(R.id.drawerLayout).openDrawer(GravityCompat.START)
            }
            R.id.settings->{
                val intent = Intent(this, SettingActivity::class.java)
                startActivity(intent)
            }
            R.id.other->{
                val intent = Intent(this, OtherActivity::class.java)
                startActivity(intent)
            }
        }
        return true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setSupportActionBar(findViewById(R.id.toolBar))
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_menu)

        val forwardBtn = findViewById<MaterialButton>(R.id.forward_btn)
        val backBtn = findViewById<MaterialButton>(R.id.back_btn)
        val leftBtn = findViewById<MaterialButton>(R.id.left_btn)
        val rightBtn = findViewById<MaterialButton>(R.id.right_btn)
        val connectBtn = findViewById<MaterialButton>(R.id.connect_btn)
        val connectText = findViewById<TextView>(R.id.connect_text)
        val ipText = findViewById<EditText>(R.id.ip_text)

        val handler = object: Handler(Looper.getMainLooper()){
            override fun handleMessage(msg: Message) {
                when(msg.what){
                    updateConnectionText -> connectText.text = "You are not connected!"
                    updateCarMoveForward -> connectText.text = "Moving Forward"
                }
            }
        }

        findViewById<NavigationView>(R.id.navView).setCheckedItem(R.id.test1)
        findViewById<NavigationView>(R.id.navView)?.setNavigationItemSelectedListener {
            when(it.itemId){
                R.id.test1->{
                    Toast.makeText(this, "Test1Navy", Toast.LENGTH_SHORT).show()
                }
                R.id.test2->{
                    Toast.makeText(this, "Test2Navy", Toast.LENGTH_SHORT).show()
                }
            }
            findViewById<DrawerLayout>(R.id.drawerLayout).closeDrawers()
            true
        }

        //val forwardBtn = findViewById<MaterialButton>(R.id.forward_btn)
         //   forwardBtn.setOnClickListener {
         //   it.setBackgroundResource(R.drawable.ic_menu)
        //}

        //val forwardBtn = findViewById<MaterialButton>(R.id.forward_btn)
        //forwardBtn.setOnLongClickListener (View.OnLongClickListener){
         //       override fun boolean onLongClick(View view){
         //           it.setBackgroundResource(R.drawable.ic_menu)
         //           return false
          //      }
        //}

//        forwardBtn.setOnLongClickListener {
//            it.setBackgroundResource(R.drawable.ic_menu);
//            false
//        }
//        forwardBtn.setOnClickListener {
//            //it.performClick()
//            it.setBackgroundResource(R.drawable.ic_menu)
//            Log.d("MainActivity", "Clicked forwardBtn")
//            //it.setBackgroundResource(R.drawable.ic_forward)
//        }
        //前按钮Listener

        forwardBtn.setOnTouchListener { view, motionEvent ->
            //if(view.isPressed) Log.d("ButtonTest", "forwardBtn Pressed")
            if(motionEvent.action == MotionEvent.ACTION_DOWN) {
                isPressed = 1
                Log.d("ButtonTest", "Held forwardBtn")
                //view.setBackgroundColor(resources.getColor(R.color.white))
                view.setBackgroundResource(R.drawable.ic_left)
//                view.onKeyLongPress(R.id.forward_btn, ){}
                thread{
                    while(isPressed == 1){
                        try{
                            if(::controlService.isInitialized){
                                Log.d("ButtonTest", "isInitialized! Sending Instruction.")
//                                controlService.checkConnect().enqueue(object: Callback<Instruction> {
//                                    override fun onResponse(
//                                        call: Call<Instruction>,
//                                        response: Response<Instruction>
//                                    ) {
//                                        val isOK = response.body();
//                                        if(isOK == Instruction.OK){
//                                            controlService.sendMove(Instruction.FORWARD)
//                                            Log.d("ButtonTest", "Sending Request ")
//                                            val msg = Message()
//                                            msg.what = updateCarMoveForward
//                                            handler.sendMessage(msg)
//                                        }
//                                    }
//
//                                    override fun onFailure(call: Call<Instruction>, t: Throwable) {
//                                        t.printStackTrace()
//                                    }
//                                })
                                val forward = Instruction("1", "forward")
                                val gsonForward = Gson().toJson(forward)
                                controlService.sendMove(gsonForward).enqueue(object: Callback<ResponseBody>{
                                    override fun onResponse(
                                        call: Call<ResponseBody>,
                                        response: Response<ResponseBody>
                                    ) {
                                        val sth = response.body()
                                    }

                                    override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                                        t.printStackTrace()
                                    }
                                })

                                Log.d("ButtonTest", "Pressing [Forward] Btn")
                            }
                        }catch (e: UninitializedPropertyAccessException){
                            val msg = Message()
                            msg.what = updateConnectionText
                            handler.sendMessage(msg)
                        }

                        Thread.sleep(1000)
                    }
                }
//              for(i in 1 .. 10){
//                  Log.d("ButtonTest", "Sending request $i")
//                  Thread.sleep(10)
//              }

//                runBlocking {
//                    for(i in 1 .. 2000000){
//                    print("$i ")
//                    delay(100)
//                    }
//                }
            }
            if(motionEvent.action == MotionEvent.ACTION_UP){
                Log.d("ButtonTest", "Drop forwardBtn")
                isPressed = 0
                view.setBackgroundResource(R.drawable.ic_forward)
            }
            view.performClick()
            true
        }

        //后按钮Listener
        backBtn.setOnTouchListener { view, motionEvent ->
            if(motionEvent.action == MotionEvent.ACTION_DOWN) {
                isPressed1 = 1
                Log.d("ButtonTest", "Held backBtn")
                view.setBackgroundResource(R.drawable.ic_right)
                thread{
                    while(isPressed1==1){
                        Log.d("ButtonTest", "Pressing [Backward] Btn")
                        Thread.sleep(1000)
                    }
                }
            }
            if(motionEvent.action == MotionEvent.ACTION_UP){
                Log.d("ButtonTest", "Drop backBtn")
                isPressed1 = 0
                view.setBackgroundResource(R.drawable.ic_back)
            }
            view.performClick()
            true
        }
        //左按钮Listener
        leftBtn.setOnTouchListener { view, motionEvent ->
            if(motionEvent.action == MotionEvent.ACTION_DOWN) {
                isPressed2 = 1
                Log.d("ButtonTest", "Held leftBtn")
                view.setBackgroundResource(R.drawable.ic_forward)
                thread{
                    while(isPressed2==1){
                        Log.d("ButtonTest", "Pressing [Left] Btn")
                        Thread.sleep(1000)
                    }
                }
            }
            if(motionEvent.action == MotionEvent.ACTION_UP){
                Log.d("ButtonTest", "Drop leftBtn")
                isPressed2 = 0
                view.setBackgroundResource(R.drawable.ic_left)
            }
            view.performClick()
            true
        }
        //右按钮Listener
        rightBtn.setOnTouchListener { view, motionEvent ->
            if(motionEvent.action == MotionEvent.ACTION_DOWN) {
                isPressed3 = 1
                Log.d("ButtonTest", "Held rightBtn")
                view.setBackgroundResource(R.drawable.ic_forward)
                thread{
                    while(isPressed3==1){
                        Log.d("ButtonTest", "Pressing [Right] Btn")
                        Thread.sleep(1000)
                    }
                }
            }
            if(motionEvent.action == MotionEvent.ACTION_UP){
                Log.d("ButtonTest", "Drop rightBtn")
                isPressed3 = 0
                view.setBackgroundResource(R.drawable.ic_right)
            }
            view.performClick()
            true
        }
//        val layoutManager = LinearLayoutManager(this)
////        val settingRecycler: RecyclerView = findViewById(R.id.settingRecycler)
////        settingRecycler.layoutManager = layoutManager
//        val adapter = SettingsAdapter(this, settingsList)
////        settingRecycler.adapter = adapter
//
        connectBtn.setOnClickListener {

            if(!::retrofit.isInitialized){
                try {
                    retrofit = Retrofit.Builder()
                        .baseUrl(ipText.text.toString())
                        .addConverterFactory(GsonConverterFactory.create())
                        .build()
                    Log.d("ConnectionTest", "connecting ${ipText.text.toString()}")
                    if(!::controlService.isInitialized){
                        controlService = retrofit.create(Service::class.java)
                        connectText.text = "Preparing to control..."
                    }
                }catch (e: IllegalArgumentException){
                    Toast.makeText(this, "Wrong ip address! Start With 'http' or 'https'", Toast.LENGTH_SHORT).show()
                }
            }

        }   // end -> connectBtn.setOnClickListener


    }   // end -> onCreate


}